package com.tasks.desktop;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import com.tasks.server.Server;
import com.tasks.server.Settings;
import com.tasks.table.User;
import com.tasks.tablemodel.Tasks;

public class TasksMainDesktop extends JFrame implements ActionListener {

	static Logger logger = Logger.getLogger(TasksMainDesktop.class);
	
	private Server server;
	private static final long serialVersionUID = -4862267243409084249L;
	
	private JTable tasks;
	
	private TasksMainDesktop()
	{
		server = new Server(Settings.load("../properties/MYSQL.settings"));
		
        // Manages the closing of the window.
        WindowListener l = new WindowAdapter()
            {
                public void windowClosing(WindowEvent e)
                {
                	exit();
                }
            };

        addWindowListener(l);

        setSize(300, 300);
        setTitle("Elite Task Manager");

        Container contentPane = getContentPane();
        setJMenuBar(createMenuBar());
        
        tasks = new JTable();
        
        contentPane.add(new JScrollPane(tasks), BorderLayout.CENTER);
        
        setVisible(true);
        
        doStuff();
	}
	
	private void doStuff()
	{
		EventQueue.invokeLater(new Runnable() {
			public void run() {
			    try 
			    {
			    	User user = User.fetchById(server, 4);
			    	Tasks t = new Tasks();
			    	t.fetchByUser(server, user);
			    	tasks.setModel(t);
			    }
			    catch (Exception ex) 
			    {
	
			    }
			}
	    });
	}
	
	private JMenuBar createMenuBar()
    {
        JMenuItem mi;
        JMenuBar mb = new JMenuBar();
     
        JMenu fileMenu = new JMenu("File");
        mb.add(fileMenu);
        
        mi = new JMenuItem("Exit");
        mi.setActionCommand("Exit");
        mi.addActionListener(this);
        fileMenu.add(mi);
        
        return mb;
    }
		
	public void actionPerformed(ActionEvent evt)
    {
        String action = evt.getActionCommand();
        
        if (action.equals("Exit"))
        {
        	exit();
        }
    }
	
	private void exit()
	{
		server.close();
		System.exit(0);
	}
	
	public static void main(String[] args) 
	{
		new TasksMainDesktop();
	}
}
